package com.auction.service.impl;

import com.auction.dto.LoginDTO;
import com.auction.dto.UserDTO;
import com.auction.dto.UserPageQueryDTO;
import com.auction.exception.BusinessException;
import com.auction.mapper.SellerInfoMapper;
import com.auction.mapper.UserMapper;
import com.auction.pojo.PageResult;
import com.auction.pojo.SellerInfo;
import com.auction.pojo.User;
import com.auction.properties.JwtProperties;
import com.auction.service.UserService;
import com.auction.utils.JwtUtil;
import com.auction.vo.UserLoginVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SellerInfoMapper sellerInfoMapper;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     * 
     * @param loginDTO
     * @return
     */
    @Override
    public UserLoginVO UserLogin(LoginDTO loginDTO) {
        // 1. 根据用户名查询用户
        User user = userMapper.selectByUsername(loginDTO.getUsername());

        // 2. 判断用户是否存在
        if (user == null) {
            throw new BusinessException("用户名或密码错误");
        }

        // 3. 判断密码是否正确
        //对前端传过来的明文密码进行md5加密处理
        String password = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new BusinessException("密码错误");
        }

        // 4. 判断用户状态
        if (user.getStatus() == 0) {
            throw new BusinessException("账号已禁用");
        }

        // 5. 生成JWT令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        // 6. 查询是否是卖家
        Integer isSeller = 0;
        SellerInfo sellerInfo = sellerInfoMapper.selectByUserId(user.getId());
        if (sellerInfo != null) {
            isSeller = 1;
        }

        // 7. 返回登录成功信息
        return UserLoginVO.builder()
                .id(user.getId())
                .name(user.getName())
                .username(user.getUsername())
                .token(token)
                .isSeller(isSeller)
                .build();
    }

    /**
     * 用户注册
     * 
     * @param userDTO
     */
    @Override
    public void register(UserDTO userDTO) {
        // 1. 判断用户名是否已存在
        User existUser = userMapper.selectByUsername(userDTO.getUsername());
        if (existUser != null) {
            throw new BusinessException("用户名已存在");
        }

        // 2. 判断身份证号是否已存在
        existUser = userMapper.selectByIdNumber(userDTO.getIdNumber());
        if (existUser != null) {
            throw new BusinessException("身份证号已被注册");
        }

        // 3. 设置用户信息
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        // 4. 加密密码
        user.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));

        // 5. 设置默认状态
        user.setStatus(1);

        // 6. 设置创建时间和更新时间
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 7. 保存用户
        userMapper.insert(user);
    }

    /**
     * 根据ID查询用户
     * 
     * @param id
     * @return
     */
    @Override
    public User getById(Long id) {
        return userMapper.selectById(id);
    }

    /**
     * 更新用户信息
     * 
     * @param userDTO
     */
    @Override
    public void update(UserDTO userDTO) {
        // 1. 判断用户是否存在
        User existUser = userMapper.selectById(userDTO.getId());
        if (existUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 2. 设置用户信息
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        // 3. 如果密码不为空，加密密码
        if (userDTO.getPassword() != null && !userDTO.getPassword().isEmpty()) {
            user.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        }

        // 4. 设置更新时间
        user.setUpdateTime(LocalDateTime.now());

        // 5. 更新用户
        userMapper.update(user);
    }

    /**
     * 分页查询用户
     * 
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public PageInfo<User> page(int pageNum, int pageSize, String name) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.selectByName(name);
        return new PageInfo<>(users);
    }

    /**
     * 分页查询用户
     *
     * @param userPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryUser(UserPageQueryDTO userPageQueryDTO) {
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        Page<User> page = userMapper.pageQueryUser(userPageQueryDTO);

        Long total = page.getTotal();
        List<User> records = page.getResult();

        return new PageResult(total, records);
    }

    /**
     * 启用禁用用户账号
     * @param status
     * @param id
     */
    @Override
    public void startOrStop( Integer status,Long id) {
        // 验证参数
        if (status != 0 && status != 1) {
            throw new RuntimeException("用户状态参数无效");
        }

        User user = User.builder()
                .status(status)
                .id(id)
                .build();
        // 更新用户状态
        userMapper.update(user);
    }

}